/*获取服务端的入口文件bundle*/
const Router = require('koa-router');
const axios = require('axios');
const MemoryFS = require('memory-fs');//就是文件的读取，只存放在内存中
const webpack = require('webpack');
const VueServerRenderer = require('vue-server-renderer');
const path = require('path');
const fs = require('fs');

const serveRender = require('./server.render.js')
const serverConfig = require('../../build/webpack.config.server.js');

const serverCompiler = webpack(serverConfig);//使用webpack运行配置文件
const mfs = new MemoryFS();
serverCompiler.outputFileSystem = mfs;//将配置文件中插件的输出路径改为内存

let bundle  //服务端的入口文件
serverCompiler.watch({},(err,stats)=>{//监听serverCompiler入口中的文件变化
    if(err) throw err
    stats = stats.toJson()
    stats.errors.forEach(err => console.log(err))
    stats.warnings.forEach(warn => console.warn(err))

    const bundlePath = path.join(
        serverConfig.output.path,
        'vue-ssr-server-bundle.json'
    )
    bundle = JSON.parse(mfs.readFileSync(bundlePath,'utf-8'));
})

const handleSSR = async(ctx) => {
    if(!bundle){
       ctx.body ='你等一会，别着急......'
       return ;
    }
    
    const clientManifestResp = await axios.get(//获取div环境下的业务json
        'http://127.0.0.1:8000/vue-ssr-client-manifest.json'
    )
    const clientManifest = clientManifestResp.data;

    const template = fs.readFileSync(//获取服务端的空模板
        path.join(__dirname,'../server.template.ejs'),
        'utf-8'
    )

    /*
        require('vue-server-renderer/server-plugin');和
        require('vue-server-renderer/client-plugin');的一个结合
    */
    const renderer = VueServerRenderer.createBundleRenderer(bundle,{ //生成一个带有标签引用的字符串
         inject:true, //关闭自动将bundle插入到默认生成的模板中
         clientManifest
    })

    await serveRender(ctx,renderer,template)
}

const router = new Router();
router.get('*',handleSSR)

module.exports = router;